import { ref, computed, Transition, reactive, onMounted, nextTick, onBeforeUnmount } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import { useRouter } from "vue-router";
import {
  BuildApprovalPolicyModelBaseData, BuildApprovalPolicyModel
  , ApprovalPolicyModelList, QueryApprovalResult, ApprovalPolicyModelDetail
} from "@/api/stu/bankBigData";
import { emitter } from "@/utils/mitt";
export function usePortrait() {
  const dataList = ref();
  const route = useRoute();
  const router = useRouter();
  const regex = /^[\u4E00-\u9FFF0-9a-zA-Z]{3,20}$/
  const customerNameRegex = /^(?!.*(.).*\1)[\u4e00-\u9fa5a-zA-Z0-9]{4,15}$/ //检验4-15个字符并且不能重复
  const createTaskVisible = ref<boolean>(false);
  const loading = ref<boolean>(false);
  const showTaskVisible = ref<boolean>(false);
  //展示详情
  const showData = reactive({
    strateName: '',
    productType: '',
    passModel: '',
    passRating: '',
    passRatingModel: '',//指数评分模型
    passSynthesisRat: '',//指数综合评分
    passSynthesisRat1: '',
    passSynthesisRat2: '',
    passSynthesisRat3: '',
    passSynthesisRat4: '',
    passSynthesisRat5: '',
    passSynthesisRat6: '',
    passSynthesisRat7: '',
    passSynthesisRat8: '',
    passLoanAmount: '',//贷款金额
    passLoanTime: '',//贷款时长
    passLoanRate: '',//贷款利率
    noPassRating: '',
    // noPassSynthesisRat1: '',
    // noPassSynthesisRat2: '',
    // noPassSynthesisRat3: '',
    // noPassSynthesisRat4: '',
    // noPassSynthesisRat5: '',
    // noPassSynthesisRat6: '',
    // noPassSynthesisRat7: '',
    // noPassSynthesisRat8: '',
    noPassIndexScore: [],
    ischeck: false,
  })
  //新建数据
  const formData = reactive({
    strateName: '',
    productType: '',
    passModel: '',
    passRating: '',
    passRatingModel: '',//指数评分模型
    passSynthesisRat: '',//指数综合评分
    passSynthesisRat1: '',
    passSynthesisRat2: '',
    passSynthesisRat3: '',
    passSynthesisRat4: '',
    passSynthesisRat5: '',
    passSynthesisRat6: '',
    passSynthesisRat7: '',
    passSynthesisRat8: '',
    passLoanAmount: '',//贷款金额
    passLoanTime: '',//贷款时长
    passLoanRate: '',//贷款利率
    noPassRating: '',
    // noPassSynthesisRat1: '',
    // noPassSynthesisRat2: '',
    // noPassSynthesisRat3: '',
    // noPassSynthesisRat4: '',
    // noPassSynthesisRat5: '',
    // noPassSynthesisRat6: '',
    // noPassSynthesisRat7: '',
    // noPassSynthesisRat8: '',
    ischeck: '0',
  })

  const productList = ref()
  const selectData = ref()
  const loanAmountList = ref()
  const loanDurationList = ref()
  const loanRateList = ref()
  const indexData = ref()
  const userCreditData = ref()
  const resultList = ref()
  const selectId = ref()
  const resultVisible = ref()
  const parameterValueMap = {
    PerformanceCapability: '履约能力指数模型',
    SpendingPower: '消费能力指数模型',
    FundingRequirements: '资金需求指数模型',
    PersonalStability: '个人稳定性指数模型',
    MaliciousOverdraft: '恶意透支指数模型',
    SocialActivity: '社交活跃性指数模型',
    OnlineShopping: '网购倾向指数模型',
    GameAddiction: '游戏沉迷指数模型',
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    pageSizes: [5, 10, 15],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "策略名称",
      prop: "policyName"
    }, {
      label: "产品类型",
      prop: "productType"
    },
    {
      label: "操作",
      prop: "operation",
      width: 300,
      slot: "operation"
    },
  ];
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      width: 120
    },
    {
      label: "客户名称",
      prop: "userName",
    },
    {
      label: "审批策略名称",
      prop: "policyName"
    }, {
      label: "产品类型",
      prop: "productType"
    }, {
      label: "审批结果",
      prop: "approvalResult",
    },
  ];
  const BtnLoading = ref<boolean>(false)
  function OUTBtnLoding() {
    setTimeout(() => {
      BtnLoading.value = false
    }, 1000)
  }
  const handleCurrentChange = val => {
    getList()
  };
  function handleSizeChange() {
    getList()
  }

  const handleCurrentChange1 = val => {
    getList2()
  };
  function handleSizeChange1() {
    getList2()
  }


  //获取任务列表
  async function getList() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize,
    };
    const respone = await ApprovalPolicyModelList(data);
    if (respone.success) {
      respone.data?.items.forEach(item => {
        item.createTime = item.createTime.substring(0, 10)
      })
      dataList.value = respone?.data.items
      pagination.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }

  const rule = {
    strateName: [
      {
        required: true,
        validator: (rule: any, value: any, callback: () => void) => {
          if (regex.test(formData.strateName) === false) {
            return callback(new Error('请输3-20个字符'))
          } else {
            // 校验通过
            return callback()
          }
        },
        trigger: ["blur", "change"],
      }
    ],
    productType: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "请选择产品类型"
      }
    ],
    passLoanTime: [
      {
        required: true,
        trigger: ["blur", "change"],
        message: "请选择贷款时长"
      }
    ],
  }
  function handleProductTypeChange() {
    formData.passLoanTime = ''
    formData.passLoanRate = ''
    const type = formData.productType
    formData.passLoanAmount = selectData.value.filter(item => item.productType == type)[0].loanAmountList[0].selectId
    loanDurationList.value = selectData.value.filter(item => item.productType == type)[0].loanDurationList
    loanRateList.value = selectData.value.filter(item => item.productType == type)[0].lendingRateList
  }

  function handleTimeChange(row) {
    if (formData.passLoanTime == '分期偿还') {
      formData.passLoanRate = '5.9%'
      return
    }
    const sortNo = loanDurationList.value.filter(item => item.selectId == formData.passLoanTime)[0].sortNo
    formData.passLoanRate = loanRateList.value.filter(item => item.sortNo == sortNo)[0].selectId
  }
  function saveNew(formEl: FormInstance | undefined) {
    formEl.validate(async (valid) => {
      if (!valid) return
      if (valid) {
        BtnLoading.value = true
        OUTBtnLoding()
        emitter.emit("getSubSelectData")
      }
    })
  }
  emitter.on("saveStrategicModelBuild", async (row) => {
    const list = JSON.parse(row)
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      policyName: formData.strateName,
      productType: formData.productType,
      passCreditScoreModelId: formData.passModel,
      passCreditScore: Number(formData.passRating),
      passPortraitIndexSystemId: formData.passRatingModel,
      passIndexTotalScore: Number(formData.passSynthesisRat),
      passPerformanceCapabilityRadio: Number(formData.passSynthesisRat1),
      passSpendingPowerRadio: Number(formData.passSynthesisRat2),
      passFundingRequirementsRadio: Number(formData.passSynthesisRat3),
      passPersonalStabilityRadio: Number(formData.passSynthesisRat4),
      passMaliciousOverdraftRadio: Number(formData.passSynthesisRat5),
      passSocialActivityRadio: Number(formData.passSynthesisRat6),
      passOnlineShoppingRadio: Number(formData.passSynthesisRat7),
      passGameAddictionRadio: Number(formData.passSynthesisRat8),
      passLoanAmount: formData.passLoanAmount,
      passLoanDuration: formData.passLoanTime,
      passLendingRate: formData.passLoanRate,
      noPassCreditScoreModelId: formData.passModel,
      noPassCreditScore: Number(formData.noPassRating),
      IsOtherConditionMan: formData.ischeck == true ? '1' : '0',
      PassApprovalMethod: '',
      noPassIndexScore: []
    }
    list.forEach(item => {
      data.noPassIndexScore.push({
        indexScore: item.times,
        indexCode: item.term,
        operatorStr: item.rather == '1' ? '>' : '<',
        portraitIndexSystemId: formData.passRatingModel
      })
    });
    data.studentAnswer = JSON.stringify(data)
    let res = await BuildApprovalPolicyModel(data)
    if (res.status == 200) {
      ElMessage.success(res.msg);
      createTaskVisible.value = false
      for (let variable in formData) {
        formData[variable] = '';
      }
      getList()
    } else {
      ElMessage.error(res.msg);
    }
  })

  function checkResultList(row) {
    selectId.value = row.approvalPolicyModelId
    getList2()
  }

  async function checkDetail(row) {
    selectId.value = row.approvalPolicyModelId
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      detailId: row.approvalPolicyModelId,
    }
    let res = await ApprovalPolicyModelDetail(data)
    if (res.success) {
      showData.strateName = res?.data.policyName
      showData.productType = res?.data.productType
      showData.passModel = res?.data.passCreditScoreModelId
      showData.passRating = res?.data.passCreditScore
      showData.passRatingModel = res?.data.passPortraitIndexSystemId
      showData.passSynthesisRat = res?.data.passIndexTotalScore
      showData.passSynthesisRat1 = res?.data.passPerformanceCapabilityRadio
      showData.passSynthesisRat2 = res?.data.passSpendingPowerRadio
      showData.passSynthesisRat3 = res?.data.passFundingRequirementsRadio
      showData.passSynthesisRat4 = res?.data.passPersonalStabilityRadio
      showData.passSynthesisRat5 = res?.data.passMaliciousOverdraftRadio
      showData.passSynthesisRat6 = res?.data.passSocialActivityRadio
      showData.passSynthesisRat7 = res?.data.passOnlineShoppingRadio
      showData.passSynthesisRat8 = res?.data.passGameAddictionRadio
      showData.passLoanAmount = res?.data.passLoanAmount
      showData.passLoanTime = res?.data.passLoanDuration
      showData.passLoanRate = res?.data.passLendingRate
      showData.noPassRating = res?.data.noPassCreditScore
      showData.noPassIndexScore = res?.data.noPassIndexScore
      showData.ischeck = res?.data.isOtherConditionMan == '1' ? true : false
      showTaskVisible.value = true
      showData.noPassIndexScore.forEach(item => {
        item.indexCode = parameterValueMap[item.indexCode]
      })
    } else {
      ElMessage.error(res.msg);
    }
  }
  async function getList2() {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination2.currentPage,
      pageCount: pagination2.pageSize,
      detailId: selectId.value,
    };
    const respone = await QueryApprovalResult(data);
    if (respone.success) {
      resultVisible.value = true
      resultList.value = respone?.data.items
      pagination2.total = respone.data.totalCount;
    } else {
      ElMessage.error(respone.msg);
    }
  }
  function validateInput(key) {
    console.log(formData[key]);

    if (formData[key] < -10 || formData[key] > 10) {
      // 如果输入值超出范围，则修正为最接近的边界值
      formData[key] = Math.min(Math.max(formData[key], -10), 10);
    }
  }
  onMounted(async () => {
    const data = {
      taskId: route.query.taskId,
      planId: route.query.planId,
    };
    let res = await BuildApprovalPolicyModelBaseData(data)
    if (res.success) {
      productList.value = res?.data.baseData.map(item => {
        return {
          name: item.productType,
          value: item.productType,
        }
      })
      selectData.value = res?.data.baseData
      indexData.value = res?.data.userCreditScoreData
      userCreditData.value = res?.data.indexData
    } else {
      ElMessage.error(res.msg);
    }
    getList()
  })


  onBeforeUnmount(() => {
    emitter.off("saveStrategicModelBuild")
  })
  return {
    columns,
    loading,
    dataList,
    pagination,
    formData,
    createTaskVisible,
    rule,
    handleSizeChange,
    handleCurrentChange,
    handleProductTypeChange,
    handleTimeChange,
    productList,
    selectData,
    loanAmountList,
    loanDurationList,
    loanRateList,
    indexData,
    userCreditData,
    BtnLoading,
    saveNew,
    checkResultList,
    resultList,
    pagination2,
    columns2,
    resultVisible,
    handleSizeChange1,
    handleCurrentChange1,
    showTaskVisible,
    showData,
    checkDetail,
    validateInput,
  }
}
